//
//  ViewController.swift
//  FitFontByWidth
//
//  Created by 李煜 on 2024/9/4.
//

import UIKit

class ViewController: UIViewController {

  override func viewDidLoad() {
    super.viewDidLoad()
    

    let text = "Hello, World!"
    let attributes = [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 17),
                      ]
    let textSize = (text as NSString).size(withAttributes: attributes)
    let boundingRect = text.boundingRect(with: CGSizeMake(CGFLOAT_MAX, CGFLOAT_MAX), options: [.usesLineFragmentOrigin,.usesFontLeading], context: nil)
    let bLabel = UILabel(frame: CGRect(origin: .init(x: 100, y: 100), size: boundingRect.size))
    view.addSubview(bLabel)
    let attText = NSAttributedString(string: text, attributes: attributes)
    bLabel.attributedText = attText
    bLabel.numberOfLines = 0
    bLabel.backgroundColor = .cyan
    
    let vpadding = 10.0;
    let hpadding = 20.0;
    //UILabel设置宽高获取最合适的字体
    let myLabel = UILabel()
    view.addSubview(myLabel)
    myLabel.frame.origin = CGPointMake(10, 100)
    myLabel.frame.size = CGSizeMake(50.0+hpadding, 0)
    myLabel.backgroundColor = .orange
    myLabel.text = text
    myLabel.numberOfLines = 0;
//    myLabel.font = nil 可以不设置默认是systemsize:17
//    myLabel.font = .systemFont(ofSize: 9)
    let sizeThatFitsResult = myLabel.sizeThatFits(CGSize(width: 50+hpadding, height: CGFloat.greatestFiniteMagnitude))
    myLabel.sizeToFit()  // 调整大小以适应内容
    
    let sizeToFitResult = myLabel.frame.size  // 获取 sizeToFit 计算的大小
    
    
    print("attributes: \(textSize)\n boundingRect: \(boundingRect) \n,sizeToFit: \(sizeToFitResult), \n sizeThatFits: \(sizeThatFitsResult)")
//    myLabel.
    
    
    let insetsLb = UILabel(frame: CGRectMake(10, 200, 200, 40))
    
  }
  
  
  //    uilabel根据字体获得合适的高度或者宽度
  //1.使用boundingRect 2.使用size(withAttributes
}

